#-*- coding:utf-8 -*-
from openerp import models, fields, api, _
from datetime import datetime, timedelta
from openerp.exceptions import UserError
from openerp.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT


class sale_order(models.Model):
    _inherit = "sale.order"

    @api.multi
    def action_confirm(self):
        self.check_credit_limit_ok()
        return super(sale_order, self).action_confirm()

    @api.multi
    def check_credit_limit_ok(self):
        self.ensure_one()
        domain = [
            ('order_id.partner_id', '=', self.partner_id.id),
            ('order_id.state', 'in', ['sale', 'done'])]
        order_lines = self.env['sale.order.line'].search(domain)
        # 计算没开票的订单金额
        to_invoice_amount = 0.0
        for line in order_lines:
            # not_invoiced is different from native qty_to_invoice because
            # the last one only consider to_invoice lines the ones
            # that has been delivered or are ready to invoice regarding
            # the invoicing policy. Not_invoiced consider all
            not_invoiced = line.product_uom_qty - line.qty_invoiced
            price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = line.tax_id.compute_all(
                price, line.order_id.currency_id,
                not_invoiced,
                product=line.product_id, partner=line.order_id.partner_id)
            to_invoice_amount += taxes['total_included']

        # 未确认的发票金额,不属于销售订单
        domain = [
            ('invoice_id.partner_id', '=', self.partner_id.id),
            ('invoice_id.state', '=', 'draft'),
            ('sale_line_ids', '=', False)]
        draft_invoice_lines = self.env['account.invoice.line'].search(domain)
        draft_invoice_lines_amount = 0.0
        for line in draft_invoice_lines:
            price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = line.invoice_line_tax_ids.compute_all(
                price, line.invoice_id.currency_id,
                line.quantity,
                product=line.product_id, partner=line.invoice_id.partner_id)
            draft_invoice_lines_amount += taxes['total_included']
        #可用信用额度= 客户信用额度-欠款-待开票金额-草稿发票金额
        available_credit = self.partner_id.credit_limit - self.partner_id.credit - to_invoice_amount - draft_invoice_lines_amount
        if self.amount_total > available_credit:
            raise UserError(_(u'订单已超过信用额度，请核实账款或申请增加信用额度.\n(信用额度<=(应收账款+未确认账款+在途订单金额))'))
            return False
        #逾期未付款
        # current_date = fields.Date.context_today(self)
        # domain = [
        #     ('partner_id', '=', self.partner_id.id),
        #     ('date_due', '<', current_date),
        #     ('state', '=', 'open')]
        # due_invoices = self.env['account.invoice'].search(domain)
        # due_invoices_amount = 0.0
        # for inv in due_invoices:
        #     due_invoices_amount += inv.amount_total
        # if due_invoices_amount and self.partner_id.allow_date < current_date:
        #     raise UserError(_(u'应付账款(%s)未按约定时间支付,请催促客户付款或核实收款,或申请放宽期限!')%(due_invoices_amount))
        #     return False
        return True